import java.util.*;

public class Solution {
    public List<Integer> largestDivisibleSubset(int[] nums) {
        int n = nums.length;
        int[] dp = new int[n];
        for (int i = 0; i < n; i++) dp[i] = 1;
        Arrays.sort(nums);
        int maxans = 0, maxI = -1;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < i; j++) {
                if (nums[i] % nums[j] == 0) {
                    dp[i] = Math.max(dp[i], dp[j] + 1);
                }
            }
            if (dp[i] > maxans) {
                maxans = dp[i];
                maxI = i;
            }
        }
        List<Integer> ret = new ArrayList<>();
        int lastval = nums[maxI];
        ret.add(lastval);
        for (int c = maxans - 1; c >= 1; c--) {
            for (int j = maxI - 1; j >= 0; j--) {
                if (lastval % nums[j] == 0 && dp[j] == c) {
                    lastval = nums[j];
                    ret.add(lastval);
                    break;
                }
            }
        }
        return ret;
    }
}